package service

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"time"
	"videosS_rpc/basic/config"
	__ "videosS_rpc/basic/proto"
	"videosS_rpc/pkg"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedVideosSServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {

	count, err := config.Rdb.Get(config.Ctx, "SendCount"+in.Username).Int64()
	if count > 5 {
		return nil, fmt.Errorf("短信一天发送超过限制5次,请稍后再试")
	}

	code := rand.Intn(900000) + 100000
	sendSms, err := pkg.SendSms(in.Username, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if sendSms.Code != 2 {
		return nil, fmt.Errorf("短信发送失败")
	}
	config.Rdb.Set(config.Ctx, "SendKey"+in.Username, code, time.Minute*5)
	config.Rdb.Incr(config.Ctx, "SendCount"+in.Username)
	config.Rdb.Expire(config.Ctx, "SendCount"+in.Username, time.Hour*24)
	return &__.SendSmsResp{}, nil
}
